<template>
  <!-- 已选人员列表的弹出层 -->
  <vxe-modal
    v-model="kjRyDuox"
    title="选择人员"
    width="87%"
    append-to-body
    show-footer
    esc-closable
    show-zoom
    resize
    @close="cancel"
  >
    <div style="height: 63vh; overflow-y: auto;">
      <el-card class="box-card">
        <el-row :gutter="20">
          <!-- 已选人员列表 -->
          <el-col :span="5" :xs="24">
            <el-card class="box-card">
              <div slot="header" class="clearfix" style="text-align: center;">
                <span style="font-size: 16px; color: #1890ff">已选人员列表</span>
              </div>
              <el-table
                ref="YxKjryTable"
                :header-cell-style="{ background: '#d0cece', color: '#000000', fontWeight: 'bold' }"
                :data="ktRyList"
                height="42vh"
                highlight-current-row
                :row-class-name="rowYxKjryIndex"
                @row-click="clickYxKjryRow"
                @selection-change="handleYxKjrySelectionChange"
              >
                <!--            <el-table-column type="selection" width="40" align="center"/>-->
                <el-table-column label="序号" align="center" prop="index" width="50" />
                <el-table-column label="姓名" align="center" prop="name" />
                <el-table-column label="上下移" align="center" width="60">
                  <template slot-scope="scope">
                    <el-button type="text" size="mini" :disabled="scope.$index === 0" @click="moveUp(scope.$index)">↑
                    </el-button>
                    <el-button
                      type="text"
                      size="mini"
                      :disabled="scope.$index === ktRyList.length - 1"
                      @click="moveDown(scope.$index)"
                    >↓
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column label="移除" align="center" prop="del">
                  <template slot-scope="scope">
                    <el-button type="danger" @click.native.prevent="removePerson(scope.$index,scope.row)">移除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-col>
          <!-- 人员搜索和列表 -->
          <el-col :span="19" :xs="24">
            <!-- 顶部搜索 -->
            <el-form
              v-show="showSearch"
              ref="queryForm"
              :model="queryParams"
              size="small"
              :inline="true"
              label-width="68px"
            >
              <el-form-item label="姓名" prop="name">
                <el-input
                  v-model="queryParams.name"
                  style="background-color: white !important;"
                  placeholder="请输入姓名"
                  clearable
                  size="mini"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="熟悉领域" prop="sxLy">
                <el-select v-model="queryParams.sxLy" placeholder="请选择熟悉领域" clearable size="mini">
                  <el-option
                    v-for="dict in dict.type.rcpt_sxly"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="人员分类" prop="ryFl">
                <el-select v-model="queryParams.ryFl" placeholder="请选择人员分类" clearable size="mini">
                  <el-option
                    v-for="dict in dict.type.rcpt_ryfl"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="是否专家" prop="sfZj">
                <el-select v-model="queryParams.sfZj" placeholder="请选择是否专家" clearable size="mini">
                  <el-option
                    v-for="dict in dict.type.rcpt_sf"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <!-- 人员列表 -->
            <el-table
              ref="table"
              v-loading="loading"
              height="45vh"
              :row-key="(row) => { return row.kjryId }"
              :reserve-selection="true"
              highlight-current-row
              :header-cell-style="{ background: '#d0cece', color: '#000000', fontWeight: 'bold' }"
              :data="kjryList"
              @row-click="clickRow"
              @select="handleSelection"
              @selection-change="handleSelectionChange"
            >
              <el-table-column :reserve-selection="true" type="selection" width="55" align="center" />
              <el-table-column label="序号" align="center" type="index" width="50" />
              <el-table-column label="姓名" align="center" prop="name" show-overflow-tooltip>
                <template slot-scope="scope">
                  <el-button type="text" @click="handleButtonClick(scope.row)">
                    <el-link type="primary">{{ scope.row.name }}</el-link>
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column label="性别" align="center" prop="sex" show-overflow-tooltip>
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex" />
                </template>
              </el-table-column>
              <!--      <el-table-column label="出生日期" align="center" prop="csrq" width="120" show-overflow-tooltip>-->
              <!--        <template slot-scope="scope">-->
              <!--          <span>{{ parseTime(scope.row.csrq, '{y}-{m}-{d}') }}</span>-->
              <!--        </template>-->
              <!--      </el-table-column>-->
              <el-table-column label="年龄" align="center" prop="age" />
              <el-table-column label="人员分类" align="center" prop="ryFl" show-overflow-tooltip width="120">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.rcpt_ryfl" :value="scope.row.ryFl" />
                </template>
              </el-table-column>
              <el-table-column label="是否专家" align="center" prop="sfZj" show-overflow-tooltip>
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.rcpt_sf" :value="scope.row.sfZj" />
                </template>
              </el-table-column>
              <el-table-column label="熟悉领域" align="center" prop="sxLy" show-overflow-tooltip>
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.rcpt_sxly" :value="scope.row.sxLy" />
                </template>
              </el-table-column>
              <el-table-column label="所学专业" align="center" prop="sxZy" show-overflow-tooltip />
              <el-table-column label="毕业院校" align="center" prop="byYx" show-overflow-tooltip />
              <el-table-column label="职务" align="center" prop="zw" show-overflow-tooltip />
              <el-table-column label="职称" align="center" prop="zc" width="120">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.rcpt_zc" :value="scope.row.zc" />
                </template>
              </el-table-column>
              <el-table-column label="电话" align="center" prop="phone" show-overflow-tooltip />
              <el-table-column label="QQ" align="center" prop="qq" show-overflow-tooltip />
              <!--      <el-table-column label="是否在职" align="center" prop="sfZz" show-overflow-tooltip>-->
              <!--        <template slot-scope="scope">-->
              <!--          <dict-tag :options="dict.type.rcpt_sf" :value="scope.row.sfZz"/>-->
              <!--        </template>-->
              <!--      </el-table-column>-->
              <el-table-column label="所属单位" align="center" prop="ssDw" show-overflow-tooltip />
            </el-table>

            <!-- 列表分页 -->
            <pagination
              v-show="total > 0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
          </el-col>
        </el-row>
      </el-card>
    </div>
    <!-- 底部按钮 -->
    <div slot="footer" class="dialog-footer dialog-footer-center">
      <el-button size="small" @click="submitForm">
        <svg-icon icon-class="confirm1" class-name="custom-class" />
        确 定
      </el-button>
      <el-button size="small" @click="cancel">
        <svg-icon icon-class="cancel1" class-name="custom-class" />
        取 消
      </el-button>
    </div>

    <!-- 点击姓名查看科研人员详情 -->
    <kjry-xq ref="kjryXq" />
  </vxe-modal>
</template>

<script>
import { getKjRyLabelByIds, selectKjRyLabel } from '@/api/kjry/kjry'
import KjryXq from '@/views/kjry/kjry/components/kjryXq'

export default {
  name: 'KjryDuoXName', // 科技人员多选姓名 (张三,李四,王五)
  components: { KjryXq },
  // 科技人员单选组件
  dicts: ['rcpt_sxly', 'rcpt_ryfl', 'sys_user_sex', 'rcpt_sf', 'process_business_status', 'rcpt_zc'],
  inject: ['updateKtZcRyLabel'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 是否显示弹出层
      kjRyDuox: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        sxLy: null,
        ryFl: null,
        sfZj: null,
        userId: null,
        deptId: null
      },
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      selectedRow: null, // 保存当前选中的行
      selectedYxKjryRow: null, // 保存当前选中的行
      // 科技人员表格数据
      kjryList: [],
      kjRyLable: null,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      ktRyList: [],
      kjryId: null, // 已选择的科技人员ID
      // 已选科技人员表选中数据
      checkedYxKjry: [],
      isFirstOpen: false
    }
  },
  created() {
  },
  methods: {
    // 上移方法
    moveUp(index) {
      if (index > 0) {
        const item = this.ktRyList.splice(index, 1)[0]
        this.ktRyList.splice(index - 1, 0, item)
      }
    },
    // 下移方法
    moveDown(index) {
      if (index < this.ktRyList.length - 1) {
        const item = this.ktRyList.splice(index, 1)[0]
        this.ktRyList.splice(index + 1, 0, item)
      }
    },

    // 删除已选人员
    removePerson(index, temp) {
      // console.log(index, 1111111)
      // 删除已选人员
      this.isFirstOpen = true
      const selectedRow = this.kjryList.find(item => item.kjryId === temp.kjryId)
      if (selectedRow) {
        this.$refs.table.toggleRowSelection(selectedRow, false) // 取消勾选
      }
      this.kjryId = this.kjryId.filter(item => item !== temp.kjryId)
      this.ktRyList.splice(index, 1)
      setTimeout(() => {
        this.isFirstOpen = false
      }, 100)
      // 如果ktRyList为空，清除右侧表格的选中状态
      // this.$refs.table.clearSelection()
      // 确保右侧表格的选中状态与左侧已选人员列表同步
      // this.$nextTick(() => {
      //   this.ktRyList.forEach(item => {
      //     const selectedRow = this.kjryList.find(row => row.kjryId === item.kjryId)
      //     if (selectedRow) {
      //       this.$refs.table.toggleRowSelection(selectedRow, true)
      //     }
      //   })
      // })
    },
    /** 已选科技人员序号 */
    rowYxKjryIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 已选科技人员复选框选中数据 */
    handleYxKjrySelectionChange(selection) {
      this.checkedYxKjry = selection.map(item => item.name)
      console.log(this.checkedYxKjry, 'asdadsads')
    },
    handleSelection(selection, rowData) {
      const row = JSON.parse(JSON.stringify(rowData))
      const isHaveUser = this.ktRyList.filter(item => item.kjryId === row.kjryId)
      console.log(isHaveUser.length, '是否有该人员')
      if (isHaveUser.length) {
        const indexToRemove = this.ktRyList.findIndex(item => item.kjryId === row.kjryId)
        if (indexToRemove !== -1) {
          this.ktRyList.splice(indexToRemove, 1)
          this.kjryId.splice(indexToRemove, 1)
        }
      } else {
        console.log(row, '选择的数据')
        this.ktRyList.push(row)
        this.kjryId.push(row.kjryId)
      }
      // 如果ktRyList为空，清除右侧表格的选中状态
      if (this.ktRyList.length === 0) {
        this.$refs.table.clearSelection()
      }
      this.isFirstOpen = false
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      if (!this.isFirstOpen) {
        this.ktRyList = [...selection]
        this.kjryId = selection.map(item => item.kjryId)
        console.log(this.kjryId)
      }

      // console.log(selection, '选择的数据')
      // this.ids = selection.map(item => item.kjryId)
      // this.single = selection.length !== 1
      // this.multiple = !selection.length
    },
    // 取消弹出层
    cancel() {
      this.queryParams.pageNum = 1
      this.kjRyDuox = false
      this.getList()
      this.$refs.table.clearSelection()
      this.ktRyList = []
    },
    // 提交表单
    async submitForm() {
      this.$emit('resSubmit', this.ktRyList.map(p => p.kjryId).toString())
      this.updateKtZcRyLabel(this.ktRyList)
      await this.getList()
      this.$refs.table.clearSelection()
      this.queryParams.pageNum = 1
      this.kjRyDuox = false
      // 确保右侧表格的选中状态与左侧已选人员列表同步

      this.$nextTick(() => {
        this.ktRyList.forEach(item => {
          const selectedRow = this.kjryList.find(row => row.kjryId === item.kjryId)
          if (selectedRow) {
            this.$refs.table.toggleRowSelection(selectedRow, true)
          }

          setTimeout(() => {
            this.ktRyList = []
          }, 200)
        })
      })
    },
    handleOpen(kjryId) {
      // 接收来自父组件的数据

      this.kjryId = kjryId
      this.kjRyDuox = true
      this.isFirstOpen = true
      this.getSelDataList()
      // this.initList()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 打开窗口获取已选择科研人员
    getSelDataList() {
      const that = this
      this.getList()
      getKjRyLabelByIds(that.kjryId).then(res => {
        this.ktRyList = res.data.map(item => ({
          name: item.name, // 姓名
          kjryId: item.kjryId // 科技人员ID
        }))
      })
    },
    // 查询科技人员列表
    getList() {
      return new Promise((resolve, reject) => {
        this.loading = true
        this.isFirstOpen = true
        selectKjRyLabel(this.queryParams).then(response => {
          this.kjryList = response.rows
          this.total = response.total
          this.loading = false
          resolve()
          // const table = this.$refs.table
          // table.clearSelection()
          if (this.kjryId == null) {
            console.log('没有已选择的')
            this.kjryId = []
            this.isFirstOpen = false
          } else {
            // 默认选中已有的数据
            this.$nextTick(() => {
              if (this.kjryId.length === 0) {
                this.$refs.table.clearSelection()
              }
              // 检查kjryId是否为数组
              if (!Array.isArray(this.kjryId)) {
                // 如果kjryId是一个字符串，尝试将其转换为数组
                this.kjryId = this.kjryId.split(',').map(id => id.trim())
              }
              this.kjryList.forEach(item => {
                if (this.kjryId.includes(item.kjryId)) {
                  this.$refs.table.toggleRowSelection(item, true)
                } else {
                  this.$refs.table.toggleRowSelection(item, false)
                }
              })

              this.isFirstOpen = false
            })
          }
        })
      })
    },
    // 打开窗口初始化列表
    initList() {
      this.loading = true
      const queryParamsData = {
        pageNum: 1,
        pageSize: 10000,
        name: null,
        sxLy: null,
        ryFl: null,
        sfZj: null,
        userId: null,
        deptId: null
      }
      // 查询科技人员列表
      selectKjRyLabel(queryParamsData).then(response => {
        //  response.rows
        // const table = this.$refs.table
        // table.clearSelection()
        if (this.kjryId == null) {
          console.log('没有已选择的')
        } else {
          // 默认选中已有的数据
          this.$nextTick(() => {
            // 检查kjryId是否为数组
            if (!Array.isArray(this.kjryId)) {
              // 如果kjryId是一个字符串，尝试将其转换为数组
              this.kjryId = this.kjryId.split(',').map(id => id.trim())
            }
            const dataList = []
            this.kjryId.forEach(row => {
              dataList.push(response.rows.filter(item => item.kjryId === row)[0])
            })
            this.ktRyList = dataList
          })
        }
      })
    },
    // 重置按钮操作
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 点击行操作
    clickRow(row) {
      this.isFirstOpen = true
      // 所有人员
      this.selectedRow = row // 更新选中的行
      const table = this.$refs.table
      table.toggleRowSelection(row)

      this.handleSelection(null, row)
    },
    // 点击已选人员行操作 (`clickYxKjryRow`)
    clickYxKjryRow(row) {
      this.selectedYxKjryRow = row // 更新选中的行
      const table = this.$refs.YxKjryTable
      const selectedRows = table.selection
      // 取消之前选中的行，并选中当前点击的行
      selectedRows.forEach(selectedRow => {
        table.toggleRowSelection(selectedRow)
      })
      // table.toggleRowSelection(row);
      // 已选人员
      // this.handleSelection(null, row);
      //
      // const selectedRow = this.kjryList.find(item => item.kjryId === row.kjryId);
      // if (selectedRow) {
      //   this.$refs.table.toggleRowSelection(selectedRow, false);
      // }

      // this.selectedYxKjryRow = row; // 更新选中的行
      // const table = this.$refs.YxKjryTable;
      // table.toggleRowSelection(row);
    },
    // 查询人员详情 (`handleButtonClick`)
    // 打开科研人员详情窗口。
    handleButtonClick(row) {
      this.$refs.kjryXq.handleOpen(row)
    }

  }
}
</script>

<style scoped></style>
